package fcrypt

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/des"
	"fmt"
)

func SCEncrypt(plainByte, key []byte, typ string) ([]byte, error) {
	var err error
	var block cipher.Block
	switch typ {
	case "des":
		block, err = des.NewCipher(key)
	case "3des":
		block, err = des.NewTripleDESCipher(key)
	case "aes":
		block, err = aes.NewCipher(key)
	}
	if err != nil {
		fmt.Println(err)
		return nil, err
	}

	//获取分组块的大小
	blockSize := block.BlockSize()
	//填充
	paddingByte := PKCS5Padding(plainByte, blockSize)
	//设置加密模式
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	//加密
	cipherByte := make([]byte, len(paddingByte))
	blockMode.CryptBlocks(cipherByte, paddingByte)
	return cipherByte, nil
}

func SCDecrypt(cipherByte, key []byte, typ string) ([]byte, error) {
	var err error
	var block cipher.Block
	switch typ {
	case "des":
		block, err = des.NewCipher(key)
	case "3des":
		block, err = des.NewTripleDESCipher(key)
	case "aes":
		block, err = aes.NewCipher(key)
	}
	if err != nil {
		fmt.Println(err)
		return nil, err
	}

	//获取分组块的大小
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	paddingByte := make([]byte, len(cipherByte))
	blockMode.CryptBlocks(paddingByte, cipherByte)
	plainByte := PKCS5UnPadding(paddingByte)
	return plainByte, nil
}

func PKCS5Padding(data []byte, blockSize int) []byte {
	padding := blockSize - len(data)%blockSize
	slice1 := []byte{byte(padding)}
	slice2 := bytes.Repeat(slice1, padding)
	return append(data, slice2...)
}

func ZerosPadding(data []byte, blockSize int) []byte {
	padding := blockSize - len(data)%blockSize
	slice1 := []byte{0}
	slice2 := bytes.Repeat(slice1, padding)
	return append(data, slice2...)
}

func PKCS5UnPadding(data []byte) []byte {
	unpadding := int(data[len(data)-1])
	result := data[:(len(data) - unpadding)]
	return result
}

func ZerosUnPadding(data []byte) []byte {
	return bytes.TrimRightFunc(data, func(r rune) bool {
		return r == 0
	})
}
